#include "e2d/ui/ActorEditor.h"
#include "e2d/ui/Utils.h"
#include "e2d/ui/Temps.h"


e2d::ActorEditor::ActorEditor()
	:fxcc::imgui::Layer("Actor Editor")
{
	LoadLastPath();
	Load();
}

void e2d::ActorEditor::HandleFunc()
{

	auto& sg = e2d::State::Inst();

	if (sg.m_EditActorFlag)
	{
		OnSaveData();

		m_InstPath = sg.m_EditActorPath;
		Load();

		ztclog::info("load actor %s", m_InstPath.c_str());
		sg.m_EditActorFlag = false;
	}
}

void e2d::ActorEditor::ViewFunc()
{
	if (!m_Inst)
	{
		return;
	}
	auto& io = ImGui::GetIO();

	if (ImGui::IsKeyReleased(ImGuiKey_S) && io.KeyCtrl)
	{
		OnSaveData();
	}

	ImGui::Text("%s", m_InstPath.c_str());
	
	ImNodes::BeginNodeEditor();

	auto& node = m_Inst->m_StartAnimNode;

	ImNodes::BeginNode(node.m_NodeId);
	ImGui::Text("StartNode");
	ImGui::SetNextItemWidth(100);
	ImGui::DragFloat2("Pos", &node.m_NodePos.x);
	ImNodes::BeginOutputAttribute(node.m_StartOutPin);
	ImNodes::EndOutputAttribute();
	ImNodes::EndNode();

	if (node.m_FirstRender)
	{
		ImNodes::SetNodeEditorSpacePos(node.m_NodeId, { node.m_NodePos.x, node.m_NodePos.y });
		node.m_FirstRender = false;
	}

	ImVec2 pos = ImNodes::GetNodeEditorSpacePos(node.m_NodeId);
	node.m_NodePos.x = pos.x;
	node.m_NodePos.y = pos.y;
	
	for (auto it1 : m_Inst->m_AnimationNodes)
	{
		int animNodeId = it1.first;
		auto animNode = it1.second;

		ImNodes::BeginNode(animNodeId);


		ImNodes::EndNode();
	}

	for (auto it2 : m_Inst->m_AnimTransitions)
	{
		int transId = it2.first;
		auto trans = it2.second;

	}
	ImNodes::EndNodeEditor();
}

void e2d::ActorEditor::Load()
{

	ActorLoader m_Loader;
	m_Inst = m_Loader.LoadActor(m_InstPath);

	if (m_Inst)
	{
		ztclog::info("has load the file %s", m_InstPath.c_str());
	}
}

void e2d::ActorEditor::LoadLastPath()
{
	m_InstPath = fxcc::FileUtil::ReadFileToString(CH_Path());
}

bool e2d::ActorEditor::OnSaveData()
{
	ztclog::info("Save the actor %s", m_InstPath.c_str());

	if (!m_Inst)
	{
		return false;
	}

	fxcc::yml::Serializer serializer;
	bool flag = serializer.EncodePath<e2d::AnimationController>(m_InstPath, *m_Inst);
	return flag;
}

void e2d::ActorEditor::SaveLastPath()
{
	fxcc::FileUtil::Write(CH_Path(), m_InstPath);
}

void e2d::ActorEditor::OnDestroy()
{
	SaveLastPath();
	//OnSaveData();

}

std::string e2d::ActorEditor::CH_Path()
{
	return ".cache/actor.imgui";
}


bool e2d::ActorEditor::GetMarqueeSelectionFlag()
{
	return false;
}
